<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>积分商城</title>
    <meta name="viewport" content=" initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="{$Think.config.RESOURCEURL}wx_assets/css/common.css{$Think.config.RESOURCE_VER}" rel="stylesheet">
    <script type="text/javascript" src="{$Think.config.RESOURCEURL}wx_assets/js/zepto.1.1.3.min.js{$Think.config.RESOURCE_VER}"></script>
    <script type="text/javascript" src="{$Think.config.RESOURCEURL}wx_assets/js/zepto.alert.js{$Think.config.RESOURCE_VER}"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script type="text/javascript" src="{$Think.config.RESOURCEURL}wx_assets/js/wx_share.js{$Think.config.RESOURCE_VER}"></script>
    <script src="{$Think.config.RESOURCEURL}wx_assets/js/util.js{$Think.config.RESOURCE_VER}" type="text/javascript"></script>
    <link href="{$Think.config.RESOURCEURL}wx_assets/iconfont/iconfont.css{$Think.config.RESOURCE_VER}" rel="stylesheet">
    <link href="{$Think.config.RESOURCEURL}wx_assets/micontent/materiaDetail.css{$Think.config.RESOURCE_VER}" rel="stylesheet">
    <style media="screen">
      img {
        width: 100%;
      }
      .list {
        padding: 10px 12px;
      }
      .list .item {
        display: flex;
        margin-bottom: 10px;
        background: #fff;
        padding: 10px;
      }
      .list .item .image {
        flex-shrink: 0;
        width: 100px;
        height: 100px;
        background-size: cover;
        background-position: center center;
      }
      .list .item .right-feild {
        display: flex;
        flex-grow: 1;
        flex-direction: column;
        justify-content: space-between;
        padding-left: 10px;
      }
      .list .item .right-feild .point{
        color: #f75493;
      }
      .list .item .right-feild .btn-buy{
        color: #fff;
        background: #f75493;
        align-self: baseline;
        padding: 6px 8px;
        border-radius: 4px;
      }
      .no-data {
        text-align: center;
        line-height: 40px;
      }
      #productInfo {
        position: fixed;
        left: 0;
        bottom: -250px;
      }
    </style>
</head>
<body style="background: #f0f0f0; min-height: 100vh; font-size:14px;">

  <notempty name="data.pointPic">
    <img src="{$data.pointPic}">
  </notempty>

  <ul class="list"></ul>

  <div class="mark"></div>

  <div class="productInfo" id="productInfo" style="z-index:100;"></div>
</div>
</body>

<!-- 积分列表模板 -->
<script type="text/html" id="list-tpl">
  <% if (data) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i]%>
      <li class="item">
          <div style="background-image: url('<%=item.picUrl%>');" class="image"></div>
          <div class="right-feild">
            <div class="title"><%=item.name%></div>
            <div class="point"><%=item.points%>积分</div>
            <div class="btn-buy" onclick="page.productShow(this)" data-inventory="<%=item.inventory%>" data-distributionid="<%=item.distributionId%>" data-name="<%=item.name%>" data-pid="<%=item.id%>" data-picurl="<%=item.picUrl%>" data-points="<%=item.points%>" data-inventorycount="<%=item.inventoryCount%>">立即兑换</div>
          </div>
      </li>
    <% }
  } %>
</script>

<script type="text/html" id="product-tpl">
  <div class="main">
    <div class="info">
      <div class="closeDiv"><div class="close" id="close"></div></div>
      <div class="imgDiv" align="center">
        <img class="default" src="<%=data.picUrl%>" style="width: 100%; height: 100%;">
      </div>
      <div class="p-name">
        <div class="title"><%=data.name%></div>
        <div class="price" style="overflow: hidden;height: 26px;">
          <%=data.points%>积分
        </div>
      </div>
    </div>
      <div style="max-height:250px;">
        <div class="buyNum">
          <div class="title">购买数量</div>
          <div class="numDiv">
            <a class="sub disabled" tag="sub" id="sub"></a>
            <input type="number" min="1" max="10000" step="1" value="1" class="num" id="buyNum" oninput="page.checkNum()" onblur="page.blurCheckNum()" />
            <a class="plus" tag="add" id="plus"></a>
          </div>
          <% if (data.inventory == 1) { %>
          <span class="inventory" id="inventory_count" style="display: block">&nbsp;剩余<span id="stock-num"><%=data.inventoryCount%></span>件</span>
          <% } %>
        </div>
    </div>
  </div>
  <div class="beSure">确定</div>
</script>
<script>
  function Page () {
      this.url = "{$Think.config.SERVER_HOST}call.json?customerId={$customerId}";
      this.page = 0
      this.limit = 10
      this.list = []
      this.pageCount = Math.ceil(('{$data.productList.total}' || 0)/ 10)
  };

  $.extend(Page.prototype, {
      init: function () {
          this.bindEvents()
          this._loadList(0)
          var me=this;
          $.util.initDataLoading({
              me: page,
              lastChildren:function(){
                  return $(".list .item:last-child");
              },
              page:function(){
                  return page.page;
              },
              pageCount:function(){
                  return page.pageCount;
              }
          });
      },

      bindEvents () {},

      // 获取列表信息
      _loadList: function (page,callback) {
          var that = this;
          var params = {
            start: page * this.limit,
            limit: this.limit
          }
          $.ajax({
              type: "get",
              url: this.url,
              dataType: 'json',
              data: {
                 module: "point",
                 method: "getPointProduct",
                 params: JSON.stringify(params)
              },
              success: function (res) {
                if (res.code == 0) {
                  that.list = res.data.productList.data
                  that.page = page
                  that.renderList();
                  callback()
                } else {
                    alert(res.msg);
                }
              }
          });
      },

      productShow: function(ctrl){
  			var me= this;
        var $ctrl = $(ctrl);
        var picUrl = $ctrl.data('picurl');
        var points = $ctrl.data('points');
        var inventory = $ctrl.data('inventory');
        var inventoryCount = $ctrl.data('inventorycount');
        var pid = $ctrl.data('pid');
        var name = $ctrl.data('name');
        var distributionId = $ctrl.data('distributionid');
        var html=template("product-tpl", {data: {
          picUrl: picUrl,
          points: points,
          inventory: inventory,
          inventoryCount: inventoryCount,
          name: name
        }})
        $('#productInfo').html(html);
        // 绑定加减号事件
        $('#sub').click(function() {
          var buyNum = $('#buyNum').val();
          buyNum > 1 && $('#buyNum').val(--buyNum);
          buyNum <= 1 && $("#sub").addClass("disabled");
          buyNum < inventoryCount && $("#plus").removeClass("disabled");
        });
        $('#plus').click(function() {
          var buyNum = $('#buyNum').val();
          buyNum < inventoryCount && $('#buyNum').val(++buyNum);
          buyNum > 1 && $("#sub").removeClass("disabled");
          buyNum >= inventoryCount && $("#plus").addClass("disabled");
        });
        $('.beSure').click(function() {
          var params = {
            type: 'point',
            pids: pid,
            counts: $("#buyNum").val(),
            distributionId: distributionId
          }
          $.ajax({
  						type: 'POST',
  						url: '{$Think.config.SERVER_HOST}call.json?customerId={$customerId}',
  						dataType: 'json',
  						data: {
  							 module: "product",
  							 method: "preSubmitOrder",
  							 params: JSON.stringify(params)
  						},
  						success: function(res){
                if (!res.code) {
                  var p = {
                    tplid: 1,
                    id: res.id
                  }
                  location.href = '{$Think.config.SERVER_HOST}call.html?customerId={$customerId}&module=product&method=getOrderDetail&force=1&params=' + encodeURIComponent(JSON.stringify(p))
                } else {
                  $.util.alert(res.msg)
                }
  						}
  				});
        })
        this.initClose();
  			var scroll = $(window).scrollTop();
  			$("html").css("margin-top","-"+scroll+"px");
  			this.stop();
  			if($(ctrl).hasClass("btn-disabled")){return;}
  			$("#buyNum").val(1);
  			$("#invitation").hide();
  			$("#productInfo").css("bottom",-280);
  			$(".mark").show();
  			$("#productInfo").addClass("show").css("bottom",0);
  		},

      /***禁止滑动***/
  		stop:function(){
  			$('html').addClass('noscroll');
  		},
  		/***取消滑动限制***/
  		move:function(){
  			$('html').removeClass('noscroll');
  		},

      // 验证输入的数字合法性
  		checkNum: function(){
  			var reg = /^\+?[1-9][0-9]*$/
  			var stockNum = $('#stock-num').text() * 1;
  			var buyNum =  $('#buyNum').val();
  			// 输入小数时自动向上取整
  			if (!reg.test(buyNum)) $('#buyNum').val(Math.ceil(buyNum));
  			// 有库存限制，且输入大于库存时自动取最大可购买值，并提示，加号变为不可用
        if (stockNum > 0 && $('#buyNum').val() > stockNum) {
            $('#buyNum').val(stockNum)
            $.util.alert("购买数量不能超过库存限制！");
            $("#plus").addClass("disabled");
        }
  			// 输入小于等于1的数减号变为不可用
  			if ($('#buyNum').val() <= 1) {
  				$("#sub").addClass("disabled");
  			}
  			// 输入大于等于最大值的数加号变为不可用
  			if (stockNum > 0 && $('#buyNum').val() >= stockNum) {
  				$("#sub").addClass("disabled");
  			}
  			// 当数量大于1且小于库存时，将加号、减号重置为可用状态
  			if (stockNum > 0 && buyNum > 1 && buyNum < stockNum) {
        	$("#plus").removeClass("disabled");
        	$("#sub").removeClass("disabled");
        } else if (buyNum > 1) {
  				$("#plus").removeClass("disabled");
  				$("#sub").removeClass("disabled");
  			}
  		},
  		// 失去焦点时验证
  		blurCheckNum: function(){
  			// 输入小于0的数时重置为1，并提示
  			if ($('#buyNum').val() < 1) {
  				$('#buyNum').val(1)
  				$.util.alert("至少购买一件商品！");
  				$("#sub").addClass("disabled");
  			}
  		},

      initClose: function() {
        var me = this;
        $("#close").click(function(){
  				var scroll = $("html").css("margin-top");
  				$("#productInfo").css("bottom",-280);
  				setTimeout(function(){
  					$("#productInfo").removeClass("show");
  					me.move();
  					$("#opacity").hide();$(".mark").hide();
  					$("html").css("margin-top",null);
  					$(window).scrollTop(-parseInt(scroll));
  				},500)
  			});
      },

      // 渲染列表
      renderList: function () {
        var html = ''
        if (this.page == 1 && this.list.length == 0) {
          html = '<div class="no-data">暂无数据</div>'
        } else {
          for (var i = 0; i < this.list.length; i++) {
            try {
              var imgs = JSON.parse(this.list[i].picUrl1)
              if (imgs[1]) {
                this.list[i].picUrl = imgs[1].picUrl
              }
            } catch (err) {}
          }
          html=template("list-tpl", {data: this.list})
        }
        $('.list').append(html);
      }
  });

  var page = new Page();
  page.init();
</script>
</html>
